package account

import (
  "bytes"
  "encoding/json"
  "fmt"
  "gitee.com/yizhisamoye/GoWeChat/entity/common"
  "gitee.com/yizhisamoye/GoWeChat/utils"
  "io"
  "io/ioutil"
  "mime/multipart"
  "net/http"
  "os"
  "strings"
)

/**
素材管理
*/

//上传临时素材文件（只能上传 图片、视频、文字等）
func (w WxAccount)AddTempMaterial(mediaType string,mediaFile *os.File)(*common.Material,error){
  postUrl:=fmt.Sprintf(BaseUrl+"/cgi-bin/media/upload?access_token=%s&type=%s",w.accessToken,mediaType)
  buf:=new(bytes.Buffer)
  writer:=multipart.NewWriter(buf)
  formFileWriter,err:=writer.CreateFormFile("media",mediaFile.Name())
  if err!=nil{
    return nil,err
  }
  _,err=io.Copy(formFileWriter,mediaFile)
  if err!=nil{
    return nil,err
  }
  contentType:=writer.FormDataContentType()
  writer.Close()
  resp,err:=http.Post(postUrl,contentType,buf)
  if err!=nil{
    return nil,err
  }
  result,err:= utils.CheckWxResp(resp)
  if err!=nil{
    return nil,err
  }
  material:=new(common.Material)
  if mediaType=="thumb"{
    material.MediaId=result["thumb_media_id"].(string)
  }else{
    material.MediaId=result["media_id"].(string)
  }
  material.CreateAt=int(result["created_at"].(float64))
  material.Type=mediaType
  material.Media=mediaFile
  return material,nil
}
//上传临时图文素材，该接口特殊，上传即群发
func(w WxAccount)AddTempNewsMaterial(news []common.News)(*common.Material,error){
  url:=fmt.Sprintf(BaseUrl+"/cgi-bin/media/uploadnews?access_token=%s",w.accessToken)
  result,err:=utils.SendJson(url,map[string]interface{}{
    "articles":news,
  })
  if err!=nil{
    return nil,err
  }
  m:=new(common.Material)
  m.Type=result["type"].(string)
  m.MediaId=result["media_id"].(string)
  m.CreateAt=int(result["create_at"].(float64))
  return m,nil
}
//获取临时素材文件（只能获取，图片、视频、文字等）
func(w WxAccount)GetTempMaterial(mediaId string)(*common.Material,error){
  url:=fmt.Sprintf(BaseUrl+"/cgi-bin/media/get?access_token=%s&media_id=%s",w.accessToken,mediaId)
  resp,err:=http.Get(url)
  if err!=nil{
    return nil,err
  }
  m:=new(common.Material)
  m.MediaId=mediaId
  if jsonHeaderIndex:=strings.Index(resp.Header.Get("Content-Type"),"json");jsonHeaderIndex>=0{
    //返回的是视频素材的链接
    result,err:= utils.CheckWxResp(resp)
    if err!=nil{
      return nil,err
    }
    m.Url=result["video_url"].(string)
    return m,nil
  }else{
    contentDisposition:=strings.Split(resp.Header.Get("Content-Disposition"),"=")
    fileName:="t_material_"+strings.Trim(contentDisposition[1],"\"")
    file,err:=os.OpenFile("./temp/"+fileName,os.O_RDWR|os.O_CREATE,777)
    defer file.Close()
    if err!=nil{
      return nil,err
    }
    contentByte,err:=ioutil.ReadAll(resp.Body)
    if err!=nil{
      return nil,err
    }
    file.Write(contentByte)
    m.Media=file
    return m,nil
  }
}
//添加永久图文素材
func(w WxAccount)AddNewsMaterial(news []common.News)(string,error){
  url:=fmt.Sprintf(BaseUrl+"/cgi-bin/material/add_news?access_token=%s",w.accessToken)
  result,err:=utils.SendJson(url,news)
  if err!=nil{
    return "",err
  }
  return result["media_id"].(string),err
}
//修改永久图文素材
func(w WxAccount)UpdateNewsMaterial(mediaId string,index int,news common.News)error{
  url:=fmt.Sprintf(BaseUrl+"/cgi-bin/material/update_news?access_token=%s",w.accessToken)
  _,err:=utils.SendJson(url,map[string]interface{}{
    "media_id":mediaId,
    "index":index,
    "news":news,
  })
  return err
}
//上传图文素材中的图片
func(w WxAccount)UploadNewsMaterialImg(imgFile *os.File)(string,error){
  url:=fmt.Sprintf(BaseUrl+"/cgi-bin/media/uploadimg?access_token=%s",w.accessToken)
  buf:=new(bytes.Buffer)
  writer:=multipart.NewWriter(buf)
  formFileWriter,err:=writer.CreateFormFile("media",imgFile.Name())
  if err!=nil{
    return "",err
  }
  _,err=io.Copy(formFileWriter,imgFile)
  if err!=nil{
    return "",err
  }
  contentType:=writer.FormDataContentType()
  writer.Close()
  resp,err:=http.Post(url,contentType,buf)
  if err!=nil{
    return "",err
  }
  result,err:= utils.CheckWxResp(resp)
  if err!=nil{
    return "",err
  }
  return result["url"].(string),nil
}
//添加其他类型永久素材
func(w WxAccount)AddMaterial(title,introduction,mediaType string,mediaFile *os.File)(*common.Material,error){
  url:=fmt.Sprintf(BaseUrl+"/cgi-bin/material/add_material?access_token=%s&type=%s",w.accessToken,mediaType)
  buf:=new(bytes.Buffer)
  writer:=multipart.NewWriter(buf)
  formFileWriter,err:=writer.CreateFormFile("media",mediaFile.Name())
  if err!=nil{
    return nil,err
  }
  _,err=io.Copy(formFileWriter,mediaFile)
  if err!=nil{
    return nil,err
  }
  formDescriptionWriter,err:=writer.CreateFormField("description")
  if err!=nil{
    return nil,err
  }
  descriptionBytes,_:=json.Marshal(map[string]string{
    "title":title,
    "introduction":introduction,
  })
  _,err=formDescriptionWriter.Write(descriptionBytes)
  if err!=nil{
    return nil,err
  }
  contentType:=writer.FormDataContentType()
  writer.Close()
  resp,err:=http.Post(url,contentType,buf)
  if err!=nil{
    return nil,err
  }
  result,err:= utils.CheckWxResp(resp)
  if err!=nil{
    return nil,err
  }
  material:=new(common.Material)
  material.Type=mediaType
  material.Media=mediaFile
  material.MediaId=result["media_id"].(string)
  material.Url=result["url"].(string)
  return material,nil
}
//获取永久素材
func(w WxAccount)GetMaterial(mediaId string)(*common.Material,error){
  url:=fmt.Sprintf(BaseUrl+"/cgi-bin/material/get_material?access_token=%s",w.accessToken)
  client:=http.Client{}
  dataJson,_:=json.Marshal(map[string]string{
    "media_id":mediaId,
  })
  req,_:=http.NewRequest("POST",url,bytes.NewReader(dataJson))
  resp,err:=client.Do(req)
  if err!=nil{
    return nil,err
  }
  m:=new(common.Material)
  m.MediaId=mediaId
  if jsonHeaderIndex:=strings.Index(resp.Header.Get("Content-Type"),"json");jsonHeaderIndex>=0{
    //返回的是json数据，内容为视频或图文
    result,err:= utils.CheckWxResp(resp)
    if err!=nil{
      return nil,err
    }
    if downUrl,exist:=result["down_url"];exist{
      m.Url=downUrl.(string)
    }
    resultBytes,_:=json.Marshal(result)
    err=json.Unmarshal(resultBytes,m)
    if err!=nil{
      return nil,err
    }
    return m,nil
  }else{
    contentDisposition:=strings.Split(resp.Header.Get("Content-Disposition"),"=")
    fileName:="material_"+strings.Trim(contentDisposition[1],"\"")
    file,err:=os.OpenFile("./temp/"+fileName,os.O_RDWR|os.O_CREATE,777)
    defer file.Close()
    if err!=nil{
      return nil,err
    }
    contentByte,err:=ioutil.ReadAll(resp.Body)
    if err!=nil{
      return nil,err
    }
    file.Write(contentByte)
    m.Media=file
    return m,nil
  }
}
//删除永久素材
func(w WxAccount)DeleteMaterial(mediaId string)error{
  url:=fmt.Sprintf(BaseUrl+"/cgi-bin/material/del_material?access_token=%s",w.accessToken)
  _,err:=utils.SendJson(url,map[string]string{
    "media_id":mediaId,
  })
  return err
}
//获取素材总数
func(w WxAccount)GetMaterialCount()(map[string]int,error){
  url:=fmt.Sprintf(BaseUrl+"/cgi-bin/material/get_materialcount?access_token=%s",w.accessToken)
  r,err:=utils.GetJson(url)
  if err!=nil{
    return nil,err
  }
  result:=make(map[string]int)
  result["voice_count"]=int(r["voice_count"].(float64))
  result["video_count"]=int(r["video_count"].(float64))
  result["image_count"]=int(r["image_count"].(float64))
  result["news_count"]=int(r["news_count"].(float64))
  return result,nil
}
//批量获取素材
func(w WxAccount)GetMaterialBatch(materialType string,offset,count int)([]common.Material,int,int,error){
  url:=fmt.Sprintf(BaseUrl+"/cgi-bin/material/batchget_material?access_token=%s",w.accessToken)
  result,err:=utils.SendJson(url,map[string]interface{}{
    "type":materialType,
    "offset":offset,
    "count":count,
  })
  if err!=nil{
    return nil,0,0,err
  }
  itemCount:=int(result["item_count"].(float64))
  totalCount:=int(result["total_count"].(float64))
  materials:=make([]common.Material,0)
  items:=result["item"].([]interface{})
  for _,v:=range items{
    item:=v.(map[string]interface{})
    m:=new(common.Material)
    m.MediaId=item["media_id"].(string)
    m.UpdateTime=int(item["update_time"].(float64))
    if content,exist:=item["content"];exist{
      //为图文类型素材
      newsItemByte,err:=json.Marshal((content.(map[string]interface{}))["news_item"])
      if err!=nil{
        return nil, itemCount, totalCount, err
      }
      err=json.Unmarshal(newsItemByte,m.NewsItem)
      if err!=nil{
        return nil, itemCount, totalCount, err
      }
    }else{
      //为其他类型素材
      m.Name=item["name"].(string)
      m.Url=item["url"].(string)
    }
    materials=append(materials,*m)
  }
  return materials,itemCount,totalCount,nil
}

